/*
 * Copyright 2008 Zoundry LLC, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 */
package org.zoundry.gaedt.core.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Use this to perform xpath evaluations.
 */
public class ZGaeXPath
{
    /** The xpath object is a singleton. */
    private static final ZGaeXPath sInstance = new ZGaeXPath();
    private XPath mXpath;

    /**
     * Singleton accessor.
     */
    public static final ZGaeXPath getInstance()
    {
        return sInstance;
    }

    /**
     * C'tor.
     */
    private ZGaeXPath()
    {
        XPathFactory factory = XPathFactory.newInstance();
        mXpath = factory.newXPath();
    }

    /**
     * Evaluates the given xpath expression against the given context.
     *
     * @param aXpath
     * @param aContext
     */
    public List<Node> evaluate(String aXpath, Node aContext)
    {
        try
        {
            List<Node> rval = new ArrayList<Node>();

            NodeList nodeList = (NodeList) mXpath.evaluate(aXpath, aContext, XPathConstants.NODESET);
            for (int idx = 0; idx < nodeList.getLength(); idx++)
            {
                rval.add(nodeList.item(idx));
            }
            
            return rval;
        }
        catch (XPathExpressionException e)
        {
            ZGaeUtil.logError(e);
            return Collections.EMPTY_LIST;
        }
    }

    /**
     * Evaluates the given xpath expression against the given context.
     *
     * @param aXpath
     * @param aContext
     */
    public String evaluateToString(String aXpath, Node aContext)
    {
        try
        {
            return mXpath.evaluate(aXpath, aContext);
        }
        catch (XPathExpressionException e)
        {
            ZGaeUtil.logError(e);
            return null;
        }
    }
}
